package com.strato.orm.mybatis.v1_0_0.annotation.handler;

import java.util.HashMap;
import java.util.Map;

import com.strato.base.env.v1_0_0.GlobalEnvironment;
import com.strato.orm.mybatis.v1_0_0.activator.Activator;
import com.strato.orm.mybatis.v1_0_0.annotation.handler.MybatisMapperAnnotationHandler.LocationDef;
import com.strato.orm.mybatis.v1_0_0.factory.SqlSessionFactoryProvider;

public class MybatisMapperAnnotationChangeObserver implements Runnable {

	private static int INTERVAL_LONG=3000;
	private static int INTERVAL_SHORT=500;
	
	private boolean running=true;
	private int interval=INTERVAL_SHORT;
	private StringBuffer buffer=new StringBuffer("000");
	private Map<String,LocationDef> lastLocations=new HashMap<String,LocationDef>();
	
	
	@Override
	public void run() {
		while(running){
			try {
				Map<String, LocationDef> locations = Activator.getHandler().getLocations();
				char tag='1';//changed
				if(locations.equals(lastLocations)){
					tag='0';//not change
				}
				lastLocations=new HashMap<String,LocationDef>();
				lastLocations.putAll(locations);
				buffer.deleteCharAt(0);
				buffer.append(tag);
				Thread.sleep(interval);
				if("100".equals(buffer.toString())){
					SqlSessionFactoryProvider provider = Activator.getProvider();
					synchronized(provider){
						Activator.getHandler().lock();
						try{
							provider.reset();
							provider.provide();
						}finally{
							Activator.getHandler().unlock();
						}
					}
					speeddown();
				}else if("000".equals(buffer.toString())){
					speeddown();
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	public void stop(){
		running=false;
	}
	
	public void speedup(){
		interval=INTERVAL_SHORT;
	}
	
	public void speeddown(){
		String mode=Activator.getContext().getProperty(GlobalEnvironment.KEY_MODE);
		if(GlobalEnvironment.VALUE_MODE_PRODUCTION.equals(mode)){
			interval=INTERVAL_LONG;
		}else{
			interval=INTERVAL_SHORT;
		}
	}
}
